/* eslint-disable react/prop-types */
import React from 'react';
import {Form, Button, Tree} from 'antd';
import Api from '@/api/index';
import {withRouter} from 'react-router-dom';
const {TreeNode} = Tree;

class RoleForm extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            treeData: []
        }
    }

    componentDidMount() {
        //获取列表
        this.getMenuList()
    }

    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
            }
        });
    };


    onCheck = checkedKeys => {
        console.log('onCheck', checkedKeys);
        this.setState({checkedKeys});
    };

    onSelect = (selectedKeys, info) => {
        console.log('onSelect', info);
        this.setState({selectedKeys});
    };

    //菜单列表
    getMenuList = () => {
        Api.getMenuList().then(res => {
            if (res.code == 200) {
                this.setState({treeData: res.data.result})
            }
        })
    }
    renderTree = (treeData) => {
        return treeData.map((item) => {
            if (item.children && Array.isArray(item.children)) {
                return (
                    <TreeNode title={item.moduleName} key={item.id} value={item.id}>
                        {this.renderTree(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode title={item.moduleName} key={item.id} value={item.id}/>;
        });
    }

    render() {
        const {treeData} = this.state;
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 20,
                    offset: 2,
                },
            },
        };
        return (
            <Form onSubmit={this.handleSubmit}>
                <Form.Item {...tailFormItemLayout}>
                    {treeData.length>0?
                        (<Tree
                            checkable
                            onCheck={this.onCheck}
                            onSelect={this.onSelect}
                            defaultExpandAll
                        >
                            {this.renderTree(treeData)}
                        </Tree>):null}
                </Form.Item>

                <Form.Item style={{marginTop: '30px', textAlign: 'center'}}>
                    <Button className="submit_btn" type="default">取消</Button>
                    <Button className="submit_btn" type="primary" htmlType="submit">确定</Button>
                </Form.Item>
            </Form>
        );
    }
}

export default Form.create()(withRouter(RoleForm));
